package com.lkl.hystrixdemo.order.aspect;

import com.lkl.hystrixdemo.order.utils.RedisTokenUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Component
public class TokenValidAspect {

    @Autowired
    RedisTokenUtils redisTokenUtils;

    private static final String POINT_CUT = "@annotation(com.lkl.hystrixdemo.order.aspect.annotation.LklTokenValidAnnotation)";

    @Pointcut(POINT_CUT)
    public void setPointCut () {

    }

    @Around("setPointCut()")
    public Object before (ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = getRequest();
        String token = request.getParameter("token");

        if (StringUtils.isEmpty(token)) {
            return "令牌无效";
        }

        if (!redisTokenUtils.isTokenValid(token)) {
            return "请不要重复提交";
        }
        return joinPoint.proceed();

    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }

    private HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getResponse();
    }

}
